<template>
  <div class="warpper-box">
    <div class="toolbar">
      <div style="font-weight: bold; font-size: 16px">批量新增数据库列标准</div>
      <el-space>
        <el-button @click="save" type="primary" size="small">保存</el-button>
        <el-button @click="back" size="small">返回</el-button>
      </el-space>
    </div>
    <div ref="sheetRef" class="sheet"></div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue';
import '@univerjs/presets/lib/styles/preset-sheets-filter.css';
import '@univerjs/presets/lib/styles/preset-sheets-core.css';
import sheetsCoreZhCN from '@univerjs/presets/preset-sheets-core/locales/zh-CN';
// import UniverPresetSheetsFilterZhCN from '@univerjs/presets/preset-sheets-filter/locales/zh-CN'
import { type FRange, UniverSheetsCorePreset } from '@univerjs/presets/preset-sheets-core';
// import { UniverSheetsFilterPreset } from '@univerjs/presets/preset-sheets-filter'
import { UniverSheetsDataValidationPreset } from '@univerjs/presets/preset-sheets-data-validation';
import UniverPresetSheetsDataValidationZhCN from '@univerjs/presets/preset-sheets-data-validation/locales/zh-CN';
import { createUniver, defaultTheme, FUniver, LocaleType, merge } from '@univerjs/presets';
import type { ISaveDatabaseColumnStandard } from '../database-column-standard';
import { dwHttp } from '@/utils/http';

defineOptions({
  name: 'BatchInsertSheet',
});
const sheetRef = ref<HTMLElement>();
let univerAPI: FUniver | undefined = undefined;
const emits = defineEmits(['back']);
defineExpose({ open });
onMounted(() => {
  const univer = createUniver({
    locale: LocaleType.ZH_CN,
    locales: {
      [LocaleType.ZH_CN]: merge({}, sheetsCoreZhCN, UniverPresetSheetsDataValidationZhCN),
    },
    theme: defaultTheme,
    presets: [
      UniverSheetsCorePreset({
        container: sheetRef.value,
        header: false,
        footer: false,
      }),
      UniverSheetsDataValidationPreset(),
      // UniverSheetsFilterPreset(),
    ],
  });
  univerAPI = univer.univerAPI;
  univerAPI.createWorkbook({
    name: 'databaseColumnStandard',
    sheets: {
      sheet1: {
        id: 'sheet1',
        name: 'sheet1',

        rowCount: 50,
        columnCount: 5,
        columnData: {
          0: { w: 150, hd: 0 },
          1: { w: 125, hd: 0 },
          2: { w: 100, hd: 0 },
          3: { w: 100, hd: 0 },
          // 4: { w: 100, hd: 0 },
          4: { w: 320, hd: 0 },
        },
        cellData: {
          0: {
            0: { v: '字段名称' },
            1: { v: '数据类型' },
            2: { v: '长度' },
            3: { v: '小数' },
            // 4: { v: '必填' },
            4: { v: '备注' },
          },
        },
      },
    },
  });

  // setFrozenRange(univerAPI, 1, 2)
  setDataValidation(univerAPI);

  const defaultRowStyle = {
    bg: {
      rgb: '#b9a42c',
    },
    cl: {
      rgb: '#fff',
    },
    ht: 2,
  };
  const workbook = univerAPI.getActiveWorkbook();
  const sheet = workbook!.getActiveSheet();
  sheet.setRowDefaultStyle(0, defaultRowStyle);

  // const workbook = univerAPI.getActiveWorkbook()
  // const sheet = workbook!.getActiveSheet()
  const range1 = sheet.getRange('A1:G1');
  const ranges = [range1];
  setWorksheetPermission(univerAPI, ranges);
});

const setWorksheetPermission = async (univerAPI: FUniver, ranges: FRange[]) => {
  const workbook = univerAPI.getActiveWorkbook();
  if (workbook === null) {
    return;
  }
  const sheet = workbook.getActiveSheet();
  const unitId = workbook.getId();
  const subUnitId = sheet.getSheetId();

  const permission = workbook.getPermission();
  const rangeProtectionPermissionEditPoint = permission.permissionPointsDefinition.RangeProtectionPermissionEditPoint;
  const res = await permission.addRangeBaseProtection(unitId, subUnitId, ranges);
  if (!res) {
    return;
  }
  // 这里的返回区别于工作表权限，因为一个子表中可能会有多个区域保护，所以 ruleId 是用来存储该权限规则的唯一 id，permissionId 是用来拼接权限点位的。
  const { permissionId } = res;
  //eslint-disable-next-line @typescript-eslint/ban-ts-comment
  //@ts-ignore
  permission.rangeRuleChangedAfterAuth$.subscribe((currentPermissionId) => {
    if (currentPermissionId === permissionId) {
      // 设置范围保护为不可编辑
      permission.setRangeProtectionPermissionPoint(unitId, subUnitId, permissionId, rangeProtectionPermissionEditPoint, false);
    }
  });
  permission.setPermissionDialogVisible(false);
};

// const setFrozenRange = (univerAPI: FUniver, row: number, column: number) => {
//   const workbook = univerAPI.getActiveWorkbook()
//   if (workbook === null) {
//     return
//   }
//   const worksheet = workbook.getActiveSheet()
//   worksheet.setFrozenRows(row)
//   worksheet.setFrozenColumns(column)
// }

const setDataValidation = (univerAPI: FUniver) => {
  const workbook = univerAPI.getActiveWorkbook();
  if (workbook === null) {
    return;
  }
  const worksheet = workbook.getActiveSheet();
  const fRange1 = worksheet.getRange('B2:B50');
  const rule = univerAPI
    .newDataValidation()
    .requireValueInList([
      'bigint',
      'binary',
      'bit',
      'blob',
      'char',
      'date',
      'datetime',
      'decimal',
      'double',
      'enum',
      'float',
      'geometry',
      'geometrycollection',
      'int',
      'intege',
      'json',
      'linestring',
      'longblob',
      'longtext',
      'mediumblob',
      'mediumtint',
      'mediumtext',
      'multilinestring',
      'multipoint',
      'multipolygon',
      'mumeric',
      'point',
      'polygon',
      'real',
      'set',
      'smallint',
      'text',
      'time',
      'timestamp',
      'tinyblob',
      'tinyint',
      'tinytext',
      'varbinary',
      'varchar',
      'year',
    ])
    .setOptions({
      showErrorMessage: true,
      error: '数据类型不正确',
    })
    .build();
  fRange1.setDataValidation(rule);

  // const fRange2 = worksheet.getRange('E2:E50')
  // const rule2 = univerAPI
  //   .newDataValidation()
  //   .requireCheckbox()
  //   .setOptions({
  //     showErrorMessage: true,
  //     error: '值必须再1到10之间',
  //   })
  //   .build()
  // fRange2.setDataValidation(rule2)
};

const save = () => {
  const activeWorkbook = univerAPI?.getActiveWorkbook();
  if (!activeWorkbook) {
    return;
  }
  const snapshot = activeWorkbook.save();
  const sheet1 = Object.values(snapshot.sheets).find((sheet) => {
    return sheet.name === 'sheet1';
  });

  if (!sheet1) throw new Error('sheet1 is not defined');
  const cellData = sheet1.cellData;
  const list: Record<string, string | number>[] = [];
  const columnJson = {
    '0': 'columnName',
    '1': 'dataType',
    '2': 'digitLength',
    '3': 'numberScale',
    '4': 'columnComment',
  };
  for (const rowIndex in cellData) {
    if (rowIndex === '0') {
      continue;
    }
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //@ts-ignore
    const _rowdata = cellData[rowIndex];
    const rowdata: Record<string, string | number> = {};
    for (const columnIndex in _rowdata) {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      //@ts-ignore
      const columName = columnJson[columnIndex];
      rowdata[columName] = _rowdata[columnIndex].v;
    }
    list.push(rowdata);
  }
  const data: ISaveDatabaseColumnStandard[] = list as unknown as ISaveDatabaseColumnStandard[];

  dwHttp({
    url: '/admin-api/modeling/database/column/standard/batch/insert',
    method: 'post',
    data: data,
  }).then(() => {
    // emits('back')
  });
};
const back = () => {
  emits('back');
};
</script>
<style lang="scss" scoped>
.warpper-box {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.toolbar {
  width: calc(100% - 50px);
  height: 40px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  vertical-align: middle;
}
.sheet {
  width: 100%;
  height: calc(100% - 50px);
  border-top: 1px solid #e3e5ea;
}
</style>
